﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using CML.Intercamber.Service.TaskManager;
using log4net;
using Quartz;
using Quartz.Impl;

namespace CML.Intercamber.Service
{
    public class TaskScheduler
    {

        private IScheduler scheduler;
        private ILog logger;

        public string Name
        {
            get { return GetType().Name; }
        }

        public void Run()
        {
            logger = LogManager.GetLogger(GetType());


            NameValueCollection properties = new NameValueCollection();
            // taille du thread pool de quartz.net (défaut 10)
            properties["quartz.threadPool.threadCount"] = "20";

            ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties);

            scheduler = schedulerFactory.GetScheduler();
            scheduler.Start();

            // chargements jobs quartz via la config XML
            IntercambersTasksConfig.LoadIntercambersTasksConfig();
            Dictionary<string, IntercambersTasksConfigElement> quartzConfs = IntercambersTasksConfig.Configs;
            BaseClusteredTaskConfiguration.Configurations = quartzConfs; // init conf pour gestion du nombre de threads
            foreach (var conf in quartzConfs)
            {
                if (conf.Value.Active == 0)
                    continue;
                logger.Info(string.Format("Chargement du job quartz pour {0} avec le cron {1} et {2} threads", conf.Key, conf.Value.CronSchedule, conf.Value.ThreadNumbers));
                Type jobClass = Type.GetType(conf.Key);
                if (jobClass != null)
                {
                    IJobDetail newJob = JobBuilder.Create(jobClass).Build();
                    ITrigger newTrigger = TriggerBuilder
                        .Create()
                        .WithCronSchedule(conf.Value.CronSchedule, x => x.WithMisfireHandlingInstructionFireAndProceed())
                        .Build();
                    scheduler.ScheduleJob(newJob, newTrigger);
                }
                else
                    logger.Error("Impossible de charger le job " + conf.Key);
            }
        }

        public void Stop()
        {
            scheduler.Shutdown();
        }

    }
}
